import { ref, onMounted, onUnmounted, computed, watch, nextTick, onActivated, onDeactivated } from 'vue'
import { useStore } from 'vuex'
import BScroll from '@better-scroll/core'
import Slide from '@better-scroll/slide'

BScroll.use(Slide)

export default function useMinSlider () {
  const store = useStore()
  const sliderWrapperRef = ref(null)
  const fullScreen = computed(() => store.state.isFullScreen)
  const playList = computed(() => store.state.playList)
  const currentIndex = computed(() => store.state.currentIndex)
  // 只有当非全屏并且点击歌曲初始化了playList才创建slider
  const sliderShow = computed(() => !fullScreen.value && playList.value.length)
  const slider = ref(null)

  onMounted(() => {
    watch(sliderShow, (newSliderShow) => {
      if (newSliderShow) {
        nextTick(() => {
          if (!slider.value) {
            slider.value = new BScroll(sliderWrapperRef.value, {
              click: true,
              scrollX: true,
              scrollY: false,
              momentum: false,
              bounce: false,
              // 手指放在滚动区时才派发事件
              probeType: 2,
              slide: {
                autoplay: false,
                loop: true
              }
            })
          } else {
            slider.value.refresh()
          }
          slider.value.goToPage(currentIndex.value, 0, 0)
          slider.value.on('slidePageChanged', ({ pageX }) => {
            store.commit('setCurrentIndex', pageX)
          })
        })
      }
    })
    watch(currentIndex, (newCurrentIndex) => {
      if (slider.value && sliderShow.value) {
        slider.value.goToPage(newCurrentIndex, 0, 0)
      }
    })
  })
  onUnmounted(() => {
    if (slider.value) {
      slider.value.destroy()
    }
  })

  onActivated(() => {
    slider.value.enable()
    slider.value.refresh()
  })
  onDeactivated(() => {
    slider.value.disable()
  })
  return {
    slider,
    sliderWrapperRef
  }
}
